<?php

/**
 * @author chenxuezhi
 * @copyright 2016
 * 西游咚咚咚
 */

namespace Ybgame\Controller;
use Common\Controller\ApiController;
use Think\Log;

class IndexController extends ApiController {
    
    const USER_UID = "ybgame:user:%s:qid:%s";  // 用户主键分享到群

    // 未授权登陆
    public function loginNotAuth()
    {
        $userid = I('userid','','string'); // 用户userid
        if(!$userid){
            $userid = uuid('Xx');
            $dateline = date('Y-m-d H:i:s');
            $ret = M('users')->add(array(
                'userid'=>$userid,
                'nickname'=>'',
                'avatar'=>'',
                'gold'=>0,
                'create_time'=>$dateline
            ));

            if($ret){
                $users['userid'] = $userid;
                $users['nickname'] = '';
                $users['avatar'] = '';
                $users['gold'] = 0;
                $users['create_time'] = $dateline;
                
                $jsons['errno'] = 0;
                $jsons['result'] = $users;
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 1;
                $jsons['msg'] = '操作失败';
                $this->ajaxReturn($jsons);
            }
        }else{
            $users = M('users')->where("userid = '$userid'")->find();
            if($users){
                if($users['types']!=4){
                    if($users['status']!=2){
                        //未授权第二次登录
                        $data2['types'] = 2;
                    }else{
                        // 授权登录
                        if(!empty($users['nickname']) && !empty($users['avatar']) && $users['types']=3){
                            $data2['types'] = 4;
                        }else{
                            $data2['types'] = 3;
                        }
                    }
                    $ret = M('users')->where("userid = '$userid'")->save($data2);
                    if(empty($ret)) {
                        $this->response(1,'操作失败');
                    }
                }

                $jsons['errno'] = 0;
                $jsons['result'] = $users;
                $this->ajaxReturn($jsons);
            }else{
                $dateline = date('Y-m-d H:i:s');
                $ret = M('users')->add(array(
                    'userid'=>$userid,
                    'nickname'=>'',
                    'avatar'=>'',
                    'gold'=>0,
                    'create_time'=>$dateline,
                    'types'=>1
                ));
                
                if($ret){
                    $users['userid'] = $userid;
                    $users['nickname'] = '';
                    $users['avatar'] = '';
                    $users['gold'] = 0;
                    $users['create_time'] = $dateline;
                    
                    $jsons['errno'] = 0;
                    $jsons['result'] = $users;
                    $this->ajaxReturn($jsons);
                }else{
                    $jsons['errno'] = 1;
                    $jsons['msg'] = '操作失败';
                    $this->ajaxReturn($jsons);
                }
            }
        }
    } 

    // 登陆接口
    public function login()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
        
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');

        if(!$code){
            $jsons['errno'] = 1;
            $jsons['msg'] = 'code不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($nickname)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '昵称不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($avatar)){
            $jsons['errno'] = 3;
            $jsons['msg'] = '头像不能为空';
            $this->ajaxReturn($jsons);
        }

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        
        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时
        $data = @file_get_contents($url, false, stream_context_create($opts)); 
        
        //$lastSql = '';
        $json2arr = $data ? @json_decode($data, true) : '';
        if(empty($json2arr['errcode'])) {
            $json = json_decode($data, true);
            
            $userId = isset($json['openid']) ? $json['openid'] : '';
            
            $map['userid'] = $userId;
            if(!$users = M('users')->where($map)->find()){
                $dateline = date('Y-m-d H:i:s');
                $ret = M('users')->add(array(
                    'userid'=>$userId,
                    'nickname'=>$nickname,
                    'avatar'=>$avatar,
                    'gold'=>0,
                    'create_time'=>$dateline,
                    'types'=>3
                ));
                
                if($ret){
                    $users['userid'] = $userId;
                    $users['nickname'] = $nickname;
                    $users['avatar'] = $avatar;
                    $users['gold'] = 0;
                    $users['create_time'] = $dateline;
                }
            // 更改则更新用户信息    
            }else if($users['nickname'] != $nickname || $users['avatar'] != $avatar){
                M('users')->where($map)->save(array(
                    'nickname'=>$nickname,
                    'avatar'=>$avatar
                ));
            }
            
            // 如果用户存在则合并
            if($users){
                $data = array_merge($json2arr, $users); // 合并数组   
            }

            
            // 返回用户最优成绩
            $ret = M('users_game_result')->where($map)->order('score desc')->find();
            $data['good_score'] = !empty($ret['score']) ? $ret['score'] : 0;
            //$lastSql = M()->getLastSql();
  
        }
        
        //$data['lastSql'] = $lastSql;
        $this->ajaxReturn($data);
    }
    
    // 排行榜
    public function rankingList()
    {
        $users = I('users','','string');
        $page = I('page',1,'int'); // 页码
        $pageNum = I('pageNum',20,'int'); // 每页数量
        $type  = I('type',1,'int'); // 1好友排行，2世界排行
        $offset = ($page - 1) * $pageNum;

        $where['black_list'] = 1;
        $ret = M('users')
            ->field('score as s,nickname,avatar,userid')
            ->where($where)
            ->order('score desc')->limit(200)->select();
        
        $jsons['errno'] = 0;
        $jsons['result'] = $ret;
        $this->ajaxReturn($jsons);
    }
    
    // 检查用户排行变化
    public function rankingChange()
    {
        $userid = I('userid','','string');
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else{
            $map['userid'] = $userid;
            $ret = M('users_game_result')->where($map)->order('create_time desc')->limit(2)->select();
            
            $jsons['errno'] = 0;
            $jsons['result'] = $ret;
            $this->ajaxReturn($jsons);            
        }

    }
    
    // 游戏复活
    public function revive()
    {
        $userid = I('userid','','string'); // 用户userid
        $gold = I('gold',0,'int'); // 复活金币
        
        $map['userid'] = $userid; 
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
        }else if(empty($gold)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '复活金币不能为空';
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户不存在';
        }else if($users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
        }else{
            $ret = M('users')->where($map)->setDec('gold',$gold);
            
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '操作成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '操作失败';
            } 
        }
        $this->ajaxReturn($jsons);   
    }
    
    // 购买角色
    public function buyRole()
    {
        $userid = I('userid','','string'); // 用户userid
        $gameRole = I('gameRole',0,'int'); // 游戏角色id
        //$type = I('type',0,'int'); // 获取类型 1.免费,2.金币购买,3.分享获取，4.未解锁
        $gameRoleList = C('GAME_ROLE'); // 角色列表
        
        $map['userid'] = $userid;
        $map['game_role'] = $gameRole;
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(!isset($gameRoleList[$gameRole])){
            $jsons['errno'] = 2;
            $jsons['msg'] = '角色不存在';
            $this->ajaxReturn($jsons);
        }else if($ret = M('users_game_role')->where($map)->find()){
            $jsons['errno'] = 3;
            $jsons['msg'] = '你已购买过此角色';
            $this->ajaxReturn($jsons);
        }else{
            
            /*if($type == 1 || $type == 3){ // 获取类型 1.免费,2.金币购买,3.分享获取，4.未解锁
                // 购买记录
                $data['userid'] = $userid;
                $data['game_role'] = $gameRole;
                $data['gold'] = $gold;
                $data['type'] = $type;
                $data['create_time'] = date('Y-m-d H:i:s');
                $ret = M('users_game_role')->add($data);
                
                if($ret){
                    $jsons['errno'] = 0;
                    $jsons['msg'] = '购买成功';
                    $this->ajaxReturn($jsons);
                }else{
                    $jsons['errno'] = 5;
                    $jsons['msg'] = '购买失败';
                    $this->ajaxReturn($jsons);
                }
            }else{ // 收费*/
                $gold = isset($gameRoleList[$gameRole]) ? $gameRoleList[$gameRole]['gold'] : 0; // 角色金币    
                $users = M('users')->where("userid = '$userid'")->find();
                if($users['gold'] < $gold){
                    $jsons['errno'] = 4;
                    $jsons['msg'] = '金币不足';
                    $this->ajaxReturn($jsons);
                }else{
                    // 开启事物
                    $model = M();
                    $model->startTrans();
                    
                    // 扣除金币
                    $ret1 = M('users')->where("userid = '$userid'")->setDec('gold',$gold);
                    
                    // 购买记录
                    $data['userid'] = $userid;
                    $data['game_role'] = $gameRole;
                    $data['gold'] = $gold;
                    $data['type'] = 2; // 金币购买
                    $data['remark'] = '金币购买';
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $ret2 = M('users_game_role')->add($data);
                    
                    if($ret1 && $ret2){
                        $model->commit();
                        
                        $jsons['errno'] = 0;
                        $jsons['msg'] = '购买成功';
                        $this->ajaxReturn($jsons);
                    }else{
                        $model->rollback();
                        
                        $jsons['errno'] = 5;
                        $jsons['msg'] = '购买失败';
                        $this->ajaxReturn($jsons);
                    }
                }
            //}

        }
    }
    
    // 分享奖励
    public function shareAward()
    {
        $userid = I('userid','','string'); // 用户userid
        $shareType = I('shareType',1,'int'); // 分享类型(1首页，2角色，3死亡,4金币不足)
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        $numConfig = array(
            1=>3, // 首页
            2=>3, // 角色
            3=>2, // 复活
            4=>9999  // 金币不足
        );
        $shareNum = isset($numConfig[$shareType]) ? $numConfig[$shareType] : 0; // 死亡分享2次，其它1次
        
        $map['userid'] = $userid;
        $map['share_type'] = $shareType;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));
        $shareCount = M('users_share_log')->where($map)->count();
        
        if(empty($userid)){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }
        
        
        if($shareCount < $shareNum){
            switch($shareType){
                case 1: // 首页
                    // 开启事物
                    $model = M();
                    $model->startTrans();
                    
                    $golds = array(200, 300, 500);
                    $gold = isset($golds[$shareCount]) ? $golds[$shareCount] : 0; // 奖励金币
                    $map1['userid'] = $userid;
                    $ret1 = M('users')->where($map1)->setInc('gold',$gold);
                    //$jsons['lastSql1'] = M()->getLastSql();
                    
                    // 分享记录
                    $data['userid'] = $userid;
                    $data['share_type'] = $shareType;
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $ret2 = M('users_share_log')->add($data);
                    //$jsons['lastSql2'] = M()->getLastSql();
                    
                    if($ret1 && $ret2){
                        $model->commit();
                        
                        $jsons['errno'] = 0;
                        $jsons['msg'] = '分享成功';
                        $this->ajaxReturn($jsons);
                    }else{
                        $model->rollback();
                        
                        $jsons['errno'] = 2;
                        $jsons['msg'] = '分享失败';
                        $this->ajaxReturn($jsons);
                    }
                break;
                
                case 2: // 角色
                    $gameRole = I('gameRole',0,'int'); // 游戏角色id
                    $gameRoleList = C('GAME_ROLE'); // 角色列表
                    
                    if(!isset($gameRoleList[$gameRole])){
                        $jsons['errno'] = 3;
                        $jsons['msg'] = '角色不存在';
                        $this->ajaxReturn($jsons);
                    }else{
                        $data['userid'] = $userid;
                        $data['game_role'] = $gameRole;
                        $data['gold'] = $gameRoleList[$gameRole]['gold'];
                        $data['type'] = $gameRoleList[$gameRole]['type'];
                        $data['remark'] = '分享获赠';
                        $data['create_time'] = date('Y-m-d H:i:s');
                        $ret = M('users_game_role')->add($data);
                        
                        if($ret){
                            $jsons['errno'] = 0;
                            $jsons['msg'] = '分享成功';
                            $this->ajaxReturn($jsons);
                        }else{
                            $jsons['errno'] = 2;
                            $jsons['msg'] = '分享失败';
                            $this->ajaxReturn($jsons);
                        } 
                    }
                break;
                
                case 3: // 复活
                    // 分享记录
                    $data['userid'] = $userid;
                    $data['share_type'] = $shareType;
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $ret = M('users_share_log')->add($data);
                    
                    if($ret){
                        $jsons['errno'] = 0;
                        $jsons['msg'] = '分享成功';
                        $this->ajaxReturn($jsons);
                    }else{
                        $jsons['errno'] = 1;
                        $jsons['msg'] = '分享失败';
                        $this->ajaxReturn($jsons);
                    }
                break;
                
                case 4: // 金币不足
                    // 开启事物
                    $model = M();
                    $model->startTrans();
                    
                    $gold = 200; // 奖励金币
                    $ret1 = M('users')->where("userid = '$userid'")->setInc('gold',$gold);
    
                
                    // 分享记录
                    $data['userid'] = $userid;
                    $data['share_type'] = $shareType;
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $ret2 = M('users_share_log')->add($data);
                    
                    if($ret1 && $ret2){
                        $model->commit();
                        
                        $jsons['errno'] = 0;
                        $jsons['msg'] = '分享成功';
                        $this->ajaxReturn($jsons);
                    }else{
                        $model->rollback();
                        
                        $jsons['errno'] = 1;
                        $jsons['msg'] = '分享失败';
                        $this->ajaxReturn($jsons);
                    }
                break;
            }
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '你已分享过，请勿重复操作';
            $this->ajaxReturn($jsons);           
        }
    }
    
    // 获取用户邀请
    public function getUserInvite()
    {
        $userid = I('userid','','string'); 
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        
        $map['I.userid'] = $userid;
        $map['I.create_time'] = array('BETWEEN',array($start_time, $end_time));
        $inviteList = M('users_invite')->alias('I')
            ->field('U.userid, U.nickname, U.avatar, I.create_time')
            ->join('INNER JOIN c_users U ON U.userid = I.invited_userid')
            ->where($map)
            ->select();
            
        $jsons['errno'] = 0;
        $jsons['result'] = $inviteList;
        $this->ajaxReturn($jsons);
    }
    
    // 邀请记录
    public function inviteRecord()
    {
        $userid = I('userid','','string');
        $invited_userid = I('invited_userid','','string');
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        
        $map['userid'] = $userid;
        $map['invited_userid'] = $invited_userid;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));
        
        
        if(empty($invited_userid) || $invited_userid == 'undefined'){
            $jsons['errno'] = 1;
            $jsons['msg'] = '被邀请人userid不能为空';
            $this->ajaxReturn($jsons);
        }else if($userid == $invited_userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '不能邀请自己';
            $this->ajaxReturn($jsons);
        }else if($ret = M('users_invite')->where($map)->find()){ 
            $jsons['errno'] = 3;
            $jsons['msg'] = '已被邀请过';
            $this->ajaxReturn($jsons);
        }else{
            $data['userid'] = $userid;
            $data['invited_userid'] = $invited_userid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M('users_invite')->add($data);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '邀请成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '邀请失败';
                $this->ajaxReturn($jsons);
            }
        }
    }
    
    // 获取用户信息
    public function getUserInfo(){
        $userid = I('userid','','string');
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }
        
        $map['userid'] = $userid;
        $users = M('users')->where($map)->find();
        if($users){
            
            // 用户最优成绩
            $ret = M('users_game_result')->where($map)->order('score desc')->find();
            $users['good_score'] = !empty($ret['score']) ? $ret['score'] : 0;
            
            $jsons['errno'] = 0;
            $jsons['result'] = $users;            
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户不存在';
        }

        $this->ajaxReturn($jsons);
    }
    
    // 获取游戏角色
    public function getGameRole()
    {
        $userid = I('userid','','string');
        $gameRoleList = C('GAME_ROLE'); 
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }
        
        $map['userid'] = $userid;
        $ret = M('users_game_role')->where($map)->getField('game_role,gold',true);
        
        foreach($gameRoleList as $k=>$items){
            if(isset($ret[$k]) || $items['type'] == 1){
                $gameRoleList[$k]['buyed'] = true;
            }else{
                $gameRoleList[$k]['buyed'] = false;
            }
        }
        
        $jsons['errno'] = 0;
        $jsons['result'] = $gameRoleList;
        $this->ajaxReturn($jsons);
    }
    
    // 设置金币
    public function setGold()
    {
        $userid = I('userid','','string'); // 用户userid
        $type = I('type','inc','string'); // 操作类型：inc增加，dec减少
        $gold = I('gold',0,'int'); // 金币
        
        $map['userid'] = $userid;
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户不存在';
            $this->ajaxReturn($jsons);
        }else if($gold < 0){
            $jsons['errno'] = 3;
            $jsons['msg'] = '金币不能小于0';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec' && $users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec'){ // 减少
            $ret = M('users')->where($map)->setDec('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '扣减成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '扣减失败';
            }
            $this->ajaxReturn($jsons);
        }else if($type == 'inc'){ // 增加
            $ret = M('users')->where($map)->setInc('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '增加成功';  
            }else{
                $jsons['errno'] = 6;
                $jsons['msg'] = '增加失败';
            }
            $this->ajaxReturn($jsons);
        }else{
            $jsons['errno'] = 7;
            $jsons['msg'] = '操作类型不正确';
            $this->ajaxReturn($jsons);
        }
    }
  
    // 记录游戏成绩
    public function addGameResult()
    {
        $userid = I('userid','','string');
        $score = I('score',0,'int');
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');

        if(strlen($userid) == 30){
            $jsons['errno'] = 1;
            $jsons['msg'] = '游客不记录成绩';
            $this->ajaxReturn($jsons);
        }else if($userid == 'undefined' || $nickname == 'undefined' || $avatar == 'undefined'){
            $jsons['errno'] = 2;
            $jsons['msg'] = '字段不能为undefined';
            $this->ajaxReturn($jsons);
        }else if(!$userid){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($score)){
            $jsons['errno'] = 4;
            $jsons['msg'] = '用户成绩不能为空';
            $this->ajaxReturn($jsons);
        }else{
            $data['userid'] = $userid;
            $data['score'] = $score;
            $data['nickname'] = $nickname;
            $data['avatar'] = $avatar;
            $data['create_time'] = date('Y-m-d H:i:s');

            $map['userid'] = $userid;
            $userInfo = M('users')->field('score')->where($map)->find();

            if( $score > $userInfo['score'] ) {
               
                $param['score'] = $score;
                $param['update_time'] = date('Y-m-d H:i:s');
                M('users')->where($map)->save($param);

            }

            if($ret = M('users_game_result')->add($data)){
                $jsons['errno'] = 0;
                $jsons['msg'] = '添加成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '添加失败';
                $this->ajaxReturn($jsons);
            }                  
        }
    }
    
    // 向房间推送消息
    public function pushMsg()
    {
        $roomId = I('roomId',0,'string');
        $state = I('state',1,'int'); // 1好友加入, 2开始游戏, 3放弃游戏, 4同步游戏界面
        $msg = I('msg','','string');
        $plus = I('plus','','string');
        
        $contents['roomId'] = $roomId;
        $contents['state'] = $state;
        $contents['msg'] = $msg;
        $contents['plus'] = $plus;
        $jsons['state'] = $this->sendMsg($contents);
        $this->ajaxReturn($jsons);
    }
    
    // 解密数据
    public function cryptData()
    {
        $appid = C('APPID'); // Appid
        $sessionKey = I('sessionKey','','string'); // sessionKey
        $encryptedData = I('encryptedData','','string'); // 加密数据
        $iv = I('iv','','string');
        $userid = I('userid','','string'); // 用户userid

        $pc = new \Org\Util\WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        
        $data = $data ? json_decode($data, true) : '';
        $openGId = isset($data['openGId']) ? $data['openGId'] : 0;

        $redis = REDIS('activity');
        $userKey = sprintf(self::USER_UID,$userid,$openGId);  //用户主键分享到群
        $shareKey = $redis->get($userKey);
        if( $shareKey > 0 ) {
            $this->response(2,'每日同一群只能分享一次');
        }
        
        if ( $errCode == 0 ) {  // 解密成功
         
            $evening = date('Y-m-d 23:59:59'); //每日23点59分
            $redis->set($userKey,1);  // 标记
            $redis->exprieAt($userKey,strtotime($evening)); // 每日23点59分过期

            $jsons['errno'] = 0;
            $jsons['msg'] = '成功解密';
            //$jsons['result'] = $data ? json_decode($data, true) : '';
            $this->ajaxReturn($jsons);
        } else{
            $jsons['errno'] = $errCode;
            $jsons['msg'] = '解密失败';
            $this->ajaxReturn($jsons);
        }
    }

    // 获取SessionKey
    public function getSessionKey()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
                        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时5s
        $data = @file_get_contents($url, false, stream_context_create($opts)); 
        
        $data = $data ? @json_decode($data, true) : '';
        $jsons['errno'] = 0;
        $jsons['result'] = $data;
        $this->ajaxReturn($jsons);
    }
    
    public function test()
    {
        $room_id = $_REQUEST['room_id'];
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 0);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        $contents = array('roomId'=>$room_id, 'order_sn'=>123);
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        echo fread($client, 8192);
    }
    
    // Socket发送数据
    private function sendMsg($contents)
    {
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        return fread($client, 8192);  
    }

    // 获取服务器当前时间
    public function getServerTime(){
        $time = time();
        $this->response(0, "ok",$time);
    }

}